package dobest.ray.com.jiongjiong.views.chart;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import dobest.ray.com.jiongjiong.R;
import dobest.ray.com.jiongjiong.bean.ViewPoint;


/**
 * Created by wangl01 on 2016/1/28.
 */
public class MultipleChartView extends View {
	private int width;
	private int height;
	private float unitlengthX = 0;// X轴的单位长度
	private float unitlengthY = 0;// Y轴单位长度
	private static final int MARGIN_VALUE = 20;

	private ViewPoint originPoint;// 原点坐标

	private Paint p1;
	private Paint p2;
	private Paint p3;
	private Paint p4;
	private Paint textPaint;
	private Paint netPaint;
	private Paint circlePaint;

	private List<List<ViewPoint>> AllPoints = new ArrayList<List<ViewPoint>>();
	private float maxDataX = 0;// X轴数据最大值
	private float maxDataY = 0;// Y轴数据最大值
	private float minDataX = 0;// X轴数据最大值
	private float minDataY = 0;// Y轴数据最大值
	private int maxLenthList = 0;// 长度最大的list

	private static final String TAG = "wanglei";

	private int currentDrawPosition = 1;// 当前画的点位置
	private int radis = 10;// 画质圆的半径
	private int bigRadis = 20;// da圆的半径
	private boolean isFinish = false;// 是否数据加载完成
	private float rateX = 0;// X轴对应值比率
	private float rateY = 0;// X轴对应值比率

	private float cUnitsX;// x刻度单位
	private float cUnitsY;// y刻度单位
	private PopupWindow popupWindow;// 点击点弹出

	private Context context;

	public MultipleChartView(Context context) {
		super(context);
		this.context = context;
		init();

	}

	public MultipleChartView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		init();
	}

	public MultipleChartView(Context context, AttributeSet attrs,
			int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		this.context = context;
		init();
	}

	private void init() {
		initPaints();
	}

	/**
	 * 初始化所有画笔
	 */
	private void initPaints() {
		p1 = new Paint();
		p1.setStyle(Paint.Style.STROKE);
		p1.setStrokeWidth(6);
		p1.setAntiAlias(true);
		p1.setColor(Color.BLUE);

		p2 = new Paint();
		p2.setStyle(Paint.Style.STROKE);
		p2.setStrokeWidth(6);
		p2.setAntiAlias(true);
		p2.setColor(Color.GREEN);

		p3 = new Paint();
		p3.setStyle(Paint.Style.STROKE);
		p3.setStrokeWidth(6);
		p3.setAntiAlias(true);
		p3.setColor(Color.RED);

		p4 = new Paint();
		p4.setStyle(Paint.Style.STROKE);
		p4.setStrokeWidth(6);
		p4.setAntiAlias(true);
		p4.setColor(Color.YELLOW);

		textPaint = new Paint();
		textPaint.setTextSize(20);
		textPaint.setStyle(Paint.Style.STROKE);
		textPaint.setStrokeWidth(1);
		textPaint.setAntiAlias(true);
		textPaint.setColor(Color.BLUE);

		netPaint = new Paint();
		netPaint.setStyle(Paint.Style.STROKE);
		netPaint.setStrokeWidth(1);
		netPaint.setAntiAlias(true);
		netPaint.setAlpha(1);
		netPaint.setColor(Color.BLACK);

		circlePaint = new Paint();
		circlePaint.setStyle(Paint.Style.FILL_AND_STROKE);
		circlePaint.setStrokeWidth(6);
		circlePaint.setAntiAlias(true);
		circlePaint.setColor(Color.YELLOW);

	}

	@Override
	protected void onDraw(Canvas canvas) {
		// 绘制横纵坐标
		drawHVCoordinates(canvas);

		// 划线画点
		drawLineAndPoints(canvas);
	}

	/**
	 * 画特定区域的阴影
	 * 
	 * @param canvas
	 */
	private void drawShadow(Canvas canvas) {

		// 方式2
		// 实现填充
		p3.setStyle(Paint.Style.FILL);
		if (maxLenthList > 7) {
			Path path = new Path();
			path.moveTo(originPoint.dataX + 5 * unitlengthX, originPoint.dataY);

			path.lineTo(originPoint.dataX + 5 * unitlengthX, 200);
			path.lineTo(originPoint.dataX + 6 * unitlengthX, 300);

			path.lineTo(originPoint.dataX + 6 * unitlengthX, originPoint.dataY);
			canvas.drawPath(path, p3);
		}
	}

	/**
	 * 画点线
	 * 
	 * @param canvas
	 */
	private void drawLineAndPoints(Canvas canvas) {
		if (maxLenthList <= 1) {
			// 少于一个点 就不画了
			return;
		}

		for (List<ViewPoint> ps : AllPoints) {
			for (int i = 1; i < maxLenthList && i <= currentDrawPosition; i++) {
				canvas.drawLine(
						originPoint.dataX + ps.get(i - 1).dataX * rateX,
						originPoint.dataY - ps.get(i - 1).dataY * rateY,
						originPoint.dataX + ps.get(i).dataX * rateX,
						originPoint.dataY - ps.get(i).dataY * rateY, p2);
				canvas.drawCircle(originPoint.dataX + ps.get(i - 1).dataX
						* rateX, originPoint.dataY - ps.get(i - 1).dataY
						* rateY, ps.get(i - 1).isClick ? bigRadis : radis,
						circlePaint);
				if (i == maxLenthList - 1) {
					canvas.drawCircle(originPoint.dataX + ps.get(i).dataX
							* rateX, originPoint.dataY - ps.get(i).dataY
							* rateY, ps.get(i).isClick ? bigRadis : radis,
							circlePaint);
					isFinish = true;
				}
			}
		}
		currentDrawPosition++;
		Message msg = Message.obtain();
		msg.what = 0;
		mhander.sendMessageDelayed(msg, 50);
	}

	/**
	 * 绘制横纵坐标
	 * 
	 * @param canvas
	 */
	private void drawHVCoordinates(Canvas canvas) {

		if (AllPoints.size() > 0) {
			unitlengthX = (width - 80) / (maxLenthList + 1);// X轴坐标单位长度
			unitlengthY = (height - 80) / (maxLenthList + 1);// Y轴坐标单位长度
			// 画阴影
			drawShadow(canvas);
			// 纵坐标
			canvas.drawLine(originPoint.dataX, originPoint.dataY, MARGIN_VALUE,
					MARGIN_VALUE, p1);
			canvas.drawLine(MARGIN_VALUE - 10, MARGIN_VALUE + 20, MARGIN_VALUE,
					MARGIN_VALUE, p1);// 制作箭头
			canvas.drawLine(MARGIN_VALUE + 10, MARGIN_VALUE + 20, MARGIN_VALUE,
					MARGIN_VALUE, p1);// 制作箭头

			// 横坐标
			canvas.drawLine(originPoint.dataX, originPoint.dataY, width - 20,
					originPoint.dataY, p1);
			canvas.drawLine(width - 40, originPoint.dataY - 10, width - 20,
					originPoint.dataY, p1);// 制作箭头
			canvas.drawLine(width - 40, originPoint.dataY + 10, width - 20,
					originPoint.dataY, p1);// 制作箭头
			// 绘制Y网格
			for (int i = 0; i < maxLenthList + 1; i++) {
				canvas.drawLine(originPoint.dataX, originPoint.dataY - (i + 1)
						* unitlengthY, width - 20, originPoint.dataY - (i + 1)
						* unitlengthY, netPaint);
			}
			// 绘制X网格
			for (int i = 0; i < maxLenthList + 1; i++) {
				canvas.drawLine(originPoint.dataX + (i + 1) * unitlengthX,
						originPoint.dataY, originPoint.dataX + (i + 1)
								* unitlengthX, 20, netPaint);
			}

			// 画刻度
			// Y轴上的刻度与文字
			cUnitsY = (float) Math.ceil(maxDataY / maxLenthList);
			rateY = unitlengthY / cUnitsY;
			for (int i = 0; i < maxLenthList + 1; i++) {
				canvas.drawLine(originPoint.dataX, originPoint.dataY - (i + 1)
						* unitlengthY, originPoint.dataX + 20,
						originPoint.dataY - (i + 1) * unitlengthY, p1); // 刻度
				canvas.drawText(((int) cUnitsY * (i + 1)) + "",
						originPoint.dataX + 10, originPoint.dataY - (i + 1)
								* unitlengthY - 10, textPaint);// 文字
			}
			// X轴上的刻度与文字
			cUnitsX = (float) Math.ceil(maxDataX / maxLenthList);
			rateX = unitlengthX / cUnitsX;
			for (int i = 0; i < maxLenthList + 1; i++) {
				canvas.drawLine(originPoint.dataX + (i + 1) * unitlengthX,
						originPoint.dataY, originPoint.dataX + (i + 1)
								* unitlengthX, originPoint.dataY - 5, p1); // 刻度
				canvas.drawText((int) cUnitsX * (i + 1) + "", originPoint.dataX
						+ (i + 1) * unitlengthX - 5, originPoint.dataY - 5,
						textPaint);// 文字
			}
		}
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// 父容器传过来的宽度的值
		width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft()
				- getPaddingRight();

		// 父容器传过来的高度的值
		height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingLeft()
				- getPaddingRight();
		// X：20 Y：height - 20
		originPoint = new ViewPoint(MARGIN_VALUE, height - MARGIN_VALUE);
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}

	private int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 设置数据
	 * 
	 * @param AllPoints
	 */
	public void setAllPoints(List<List<ViewPoint>> AllPoints) {
		this.AllPoints.clear();
		this.AllPoints = AllPoints;
		for (List<ViewPoint> data : AllPoints) {
			int temSize = data.size();
			if (temSize > maxLenthList) {
				maxLenthList = temSize;
			}
			for (ViewPoint point : data) {
				// 获取最大X Y
				int temMaxX = point.dataX;
				int temMaxY = point.dataY;
				if (temMaxX > maxDataX) {
					maxDataX = temMaxX;
				}
				if (temMaxY > maxDataY) {
					maxDataY = temMaxY;
				}
				// 获取最小X Y
				int temMinX = point.dataX;
				int temMinY = point.dataY;
				if (temMinX < minDataX) {
					minDataX = temMinX;
				}
				if (temMinY < minDataY) {
					minDataY = temMinY;
				}
			}
		}
		invalidate();
	}

	private Handler mhander = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 0)
				invalidate();
		}
	};

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			return true;
		case MotionEvent.ACTION_MOVE:
			break;
		case MotionEvent.ACTION_UP:
			int X = (int) event.getX();
			int Y = (int) event.getY();
			judgeXY(X, Y);
			break;
		}
		return false;
	}

	int temX = -1;
	int temY = -1;

	/**
	 * 判断点击的位置 是否是在点上
	 * 
	 * @param x
	 * @param y
	 */
	private void judgeXY(int x, int y) {

		if (!isFinish) {
			return;
		}
		List<ViewPoint> all = new ArrayList<ViewPoint>();
		for (List<ViewPoint> l1 : AllPoints) {
			all.addAll(l1);
		}
		for (int i = 1; i <= all.size(); i++) {
			temX = (int) (originPoint.dataX + all.get(i - 1).dataX * rateX);
			temY = (int) (originPoint.dataY - all.get(i - 1).dataY * rateY);
			int tem = (temX - x) * (temX - x) + (temY - y) * (temY - y);
			if (tem < 30 * 30) {
				all.get(i - 1).isClick = true;
				invalidate();
				showPopupWindow(this, all.get(i - 1).dataY);
			} else {
				all.get(i - 1).isClick = false;
			}
		}

	}

	public void showPopupWindow(View parent, int value) {
		// 加载布局
		View layout = LayoutInflater.from(context).inflate(
				R.layout.item_popupwindow_toast, null);
		// 找到布局的控件
		TextView text = (TextView) layout.findViewById(R.id.tv_popup_text);
		text.setText(value + "");
		// 实例化popupWindow
		popupWindow = new PopupWindow(layout, 100, 100);
		// 控制键盘是否可以获得焦点
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		@SuppressWarnings("deprecation")
		// 获取xoff
		int xpos = manager.getDefaultDisplay().getWidth() / 2
				- popupWindow.getWidth() / 2;

		// xoff,yoff基于anchor的左下角进行偏移。
		popupWindow.showAsDropDown(parent, 0, 0);
		popupWindow.update(temX - 50, height - temY + 15, 100, 50);
		text.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 关闭popupWindow
				popupWindow.dismiss();
				popupWindow = null;
			}
		});

	}
}
